package com.song.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisUtil {
    private static final String RELEASE_LOCK_LUA_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private CountDownLatch countDownLatch;

    @Autowired
    public RedisUtil(CountDownLatch countDownLatch){
        this.countDownLatch = countDownLatch;
    }

    /**
     * 发送消息
     * @param channel
     * @param message
     */
    public void publicshMessage(String channel, String message){
        log.info("发送消息:" + message);
        redisTemplate.convertAndSend(channel, message);
    }

    /**
     * 接收消息
     * @param message
     */
    public void receiveMessage(String message){
        log.info("接收消息:" + message);
        countDownLatch.countDown();
    }

    /**
     * 获取分布式锁
     * @param key
     * @param requestId
     * @param expireTime
     * @return
     */
    public Boolean tryGetDistributeLock(String key, String requestId, long expireTime){
        return redisTemplate.opsForValue().setIfAbsent(key, requestId, expireTime, TimeUnit.SECONDS);
    }

    /**
     * 释放分布式锁
     * @param key
     * @param requestId
     */
    public void releaseDistributeLock(String key, String requestId){
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_LUA_SCRIPT, Long.class);
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(key), requestId);
    }
}
